<template>
  <div class="app-container">
    <div class="form-overview-container">
      <div class="header">
        <h2>表单管理</h2>
        <el-button type="primary" @click="showCreateDialog">新增表单</el-button>
      </div>

      <el-table :data="formList" border style="width: 100%">
        <el-table-column prop="formId" label="ID" width="60"></el-table-column>

        <el-table-column prop="name" label="表单名称" min-width="120" show-overflow-tooltip></el-table-column>

        <el-table-column label="时间" width="120">
          <template #default="{ row }">
            <div class="time-cell">
              <div>创建: {{ formatCompactTime(row.time) }}</div>
              <div v-if="row.deadline">截止: {{ formatCompactTime(row.deadline) }}</div>
              <div v-else>无截止</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="isApproval" label="结果审批" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="row.isApproval ? 'success' : 'info'" size="small">
              {{ row.isApproval ? '需' : '否' }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 保持原有操作按钮不变 -->
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button size="small" @click="showFormDetail(row)">查看</el-button>
            <el-button size="small" @click="editForm(row)">修改组件</el-button>
            <el-button size="small" @click="viewSubmissions(row)">查看提交数据</el-button>
            <el-button size="small" @click="viewReport(row)">查看报表</el-button>
            <el-button size="small" @click="downloadData(row)">下载数据</el-button>
            <el-button size="small" @click="share(row)">分享给他人填写</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 新增表单弹窗 -->
      <el-dialog :visible.sync="createVisible" title="新增表单" width="500px">
        <el-form :model="newForm" label-width="100px">
          <el-form-item label="表单名称">
            <el-input v-model="newForm.name" placeholder="请输入表单名称"></el-input>
          </el-form-item>

          <el-form-item label="开始时间">
            <el-date-picker v-model="newForm.time" type="datetime" placeholder="选择开始时间" value-format="timestamp">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="截止时间">
            <el-date-picker v-model="newForm.deadline" type="datetime" placeholder="选择截止时间" value-format="timestamp">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="需要审批">
            <el-switch v-model="newForm.isApproval"></el-switch>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="createVisible = false">取消</el-button>
          <el-button type="primary" @click="handleCreateForm" :loading="creating">确定</el-button>
        </template>
      </el-dialog>

      <!-- 查看表单详情弹窗 -->
      <el-dialog :visible.sync="detailVisible" title="表单详情" width="70%">
        <el-table :data="formComponents" border>
          <el-table-column prop="id" label="组件ID" width="100"></el-table-column>
          <el-table-column prop="name" label="名称"></el-table-column>
          <el-table-column prop="type" label="类型"></el-table-column>
          <el-table-column prop="value" label="默认值"></el-table-column>
          <el-table-column prop="order" label="排序"></el-table-column>
          <el-table-column prop="isRequired" label="必填" width="80">
            <template #default="{ row }">
              {{ row.isRequired ? '是' : '否' }}
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>

      <!-- 修改表单组件弹窗 -->
      <el-dialog :visible.sync="editVisible" title="修改表单" width="70%">
        <el-form :model="editFormData" label-width="120px">
          <div style="margin-bottom: 20px;">
            <el-button type="primary" size="small" @click="addComponent">新增组件</el-button>
          </div>
          <el-table :data="editFormComponents" border>
            <el-table-column prop="name" label="名称" width="200">
              <template #default="{ row }">
                <el-input v-model="row.name"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="type" label="类型" width="150">
              <template #default="{ row }">
                <el-select v-model="row.type">
                  <el-option label="输入框" value="input"></el-option>
                  <el-option label="文件" value="file"></el-option>
                  <el-option label="复选框" value="checkbox"></el-option>
                  <el-option label="单选框" value="radio"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="value" label="选项框选项(逗号分割)">
              <template #default="{ row }">
                <el-input v-model="row.value" :disabled="row.type === 'input' || row.type === 'file'"
                  :placeholder="(row.type === 'input' || row.type === 'file') ? '无需默认值' : ''">
                </el-input>
              </template>
            </el-table-column>
            <el-table-column prop="order" label="排序" width="200">
              <template #default="{ row }">
                <el-input-number v-model="row.order" :min="0"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column prop="isRequired" label="必填" width="100">
              <template #default="{ row }">
                <el-checkbox v-model="row.isRequired"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template #default="{ $index }">
                <el-button type="danger" size="mini" @click="removeComponent($index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
        <template #footer>
          <el-button @click="editVisible = false">取消</el-button>
          <el-button type="primary" @click="saveFormChanges">保存</el-button>
        </template>
      </el-dialog>

      <!-- 分享表单弹窗 -->
      <el-dialog :visible.sync="shareVisible" title="分享表单" width="500px">
        <div class="share-link-container">
          <p>请复制以下链接分享给他人填写：</p>
          <el-input v-model="shareLink" readonly>
            <template #append>
              <el-button @click="copyLink" icon="el-icon-document-copy"></el-button>
            </template>
          </el-input>
          <p class="share-tip">此链接可直接用于填写表单</p>
        </div>
        <template #footer>
          <el-button @click="shareVisible = false">关闭</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>


<script>
import { getFormList, getFormComponent, updateFormComponents, removeFormComponent, createForm, exportFormData } from '@/api/cd/form'

export default {
  data() {
    return {
      formList: [],
      formComponents: [],
      editFormComponents: [],
      detailVisible: false,
      editVisible: false,
      editFormData: {},
      currentFormId: null,
      createVisible: false,
      creating: false,
      newForm: {
        name: '',
        time: null,
        deadline: null,
        isApproval: false
      },
      // 新增分享相关数据
      shareVisible: false,
      shareLink: '',
      currentShareFormId: null
    }
  },
  created() {
    this.fetchFormList()
  },
  methods: {
    // 新增紧凑时间格式方法
    formatCompactTime(time) {
      if (!time) return '';
      const date = new Date(time);
      return `${date.getMonth() + 1}/${date.getDate()} ${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`;
    },
    share(row) {
      this.currentShareFormId = row.formId;
      // 生成分享链接，假设前端可以通过window.location.host获取当前主机
      const baseUrl = `${window.location.protocol}//${window.location.host}`;
      this.shareLink = `${baseUrl}/toPage?url=/cd/form/submit/${row.formId}`;
      this.shareVisible = true;
    },

    // 复制链接方法
    copyLink() {
      const input = document.createElement('input');
      input.value = this.shareLink;
      document.body.appendChild(input);
      input.select();
      document.execCommand('copy');
      document.body.removeChild(input);
      this.$message.success('链接已复制到剪贴板');
    },
    // 显示新增表单对话框（简化版）
    showCreateDialog() {
      this.newForm = {
        name: '',
        time: null,
        deadline: null,
        isApproval: false
      };
      this.createVisible = true;
    },

    // 处理表单提交（简化版）
    async handleCreateForm() {
      try {
        this.creating = true;

        const formData = {
          name: this.newForm.name,
          time: this.newForm.time,
          deadline: this.newForm.deadline,
          isApproval: this.newForm.isApproval
        };

        const res = await createForm(formData);

        this.$message.success('表单创建成功');
        this.createVisible = false;
        this.fetchFormList(); // 刷新列表
      } catch (error) {
        this.$message.error(`创建失败: ${error.message || '未知错误'}`);
      } finally {
        this.creating = false;
      }
    },
    async fetchFormList() {
      try {
        const res = await getFormList()
        this.formList = res.data
      } catch (error) {
        this.$message.error('获取表单列表失败')
      }
    },

    formatTime(time) {
      return new Date(time).toLocaleString()
    },

    // handleCreateForm() {
    //   this.$message.info('新增表单功能待实现')
    // },

    async showFormDetail(row) {
      this.currentFormId = row.formId
      try {
        const res = await getFormComponent(row.formId)
        this.formComponents = res.data
        this.detailVisible = true
      } catch (error) {
        this.$message.error('获取表单详情失败')
      }
    },
    // 新增方法：删除组件
    async removeComponent(index) {
      try {
        const component = this.editFormComponents[index];

        await this.$confirm('确定要删除这个组件吗？删除后无法恢复', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });

        // 调用API删除后端数据
        if (component.id) { // 确保组件有ID才调用删除API
          await removeFormComponent(component.id);
        }

        // 删除本地数据
        this.editFormComponents.splice(index, 1);

        // 重新排序
        this.editFormComponents.forEach((item, idx) => {
          item.order = idx + 1;
        });

        this.$message.success('删除成功');
      } catch (error) {
        if (error !== 'cancel') { // 如果不是用户取消操作
          this.$message.error('删除失败: ' + (error.message || error));
        }
      }
    },
    // 新增方法：添加组件
    addComponent() {
      this.editFormComponents.push({
        id: null, //无id,让后端生成
        name: '新组件',
        type: 'input',
        value: '',
        formId: this.currentFormId,
        order: this.editFormComponents.length + 1,
        isRequired: false
      })
    },
    async editForm(row) {
      this.currentFormId = row.formId
      try {
        const res = await getFormComponent(row.formId)
        // 转换二进制字段为布尔值
        this.editFormComponents = res.data.map(item => ({
          ...item,
          isRequired: Boolean(item.isRequired)
        }))
        // 如果没有组件，默认添加一个
        if (this.editFormComponents.length === 0) {
          this.addComponent()
        }
        this.editVisible = true
      } catch (error) {
        this.$message.error('获取表单详情失败')
      }
    },
    async saveFormChanges() {
      try {
        // 转换布尔值为二进制并处理默认值
        const componentsToSave = this.editFormComponents.map(item => {
          // 替换中文逗号为英文逗号
          let processedValue = item.value
          if (typeof processedValue === 'string') {
            processedValue = processedValue.replace(/，/g, ',')
          }

          return {
            ...item,
            isRequired: item.isRequired ? 1 : 0,
            // 对于input和file类型，强制设置为0
            value: (item.type === 'input' || item.type === 'file') ? '0' : (processedValue || '0')
          }
        })

        await updateFormComponents(componentsToSave)
        this.$message.success('修改成功')
        this.editVisible = false
      } catch (error) {
        this.$message.error('保存失败')
      }
    },

    viewSubmissions(row) {
      this.$router.push(`/cd/form/display/${row.formId}`)
    },

    viewReport() {
      this.$message.info('报表功能未上线')
    },
    async downloadData(row) {
      try {
        const response = await exportFormData(row.formId)
        this.downloadExcel(response, `导出文件_${row.formId}.xlsx`)
      } catch (error) {
        console.error('导出失败:', error)
        // 可以添加错误提示
      }
    },
    downloadExcel(blobData, fileName) {
      // 创建Blob对象
      const blob = new Blob([blobData], { type: 'application/vnd.ms-excel' })

      // 创建下载链接
      const link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      link.download = fileName

      // 触发点击下载
      document.body.appendChild(link)
      link.click()

      // 清理
      setTimeout(() => {
        document.body.removeChild(link)
        URL.revokeObjectURL(link.href)
      }, 100)
    }
    // downloadData(row) {

    //   exportFormData(row.formId).then(response => {
    //   })
    // }
  }
}
</script>

<style scoped>
.form-overview-container {
  padding: 15px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.el-table {
  margin-top: 15px;
  font-size: 13px;
}

.time-cell {
  font-size: 12px;
  line-height: 1.4;
}

/* 响应式调整 */
@media screen and (max-width: 992px) {
  .el-table {
    font-size: 12px;
  }

  .time-cell {
    font-size: 11px;
  }
}

@media screen and (max-width: 768px) {
  .header h2 {
    font-size: 16px;
  }

  .el-button {
    padding: 7px 9px;
    margin: 2px 0;
  }
}

@media screen and (max-width: 576px) {
  .form-overview-container {
    padding: 10px;
  }

  .el-button {
    padding: 6px 8px;
    font-size: 12px;
  }
}

</style>